<?php
namespace app\index\controller;
use app\admin\model\steward\Apps;
use app\admin\model\steward\AppsVersion;
use app\admin\model\steward\Category;
use app\common\lib\Storage;
use think\facade\App;

class Appshop extends Base
{
    //应用主页
    public function index()
    {
        $where = [];

        $category = $this->request->param("category",0,'intval');
        $isfree   = $this->request->param("isfree",0);

        if($category!=0)
        {
            array_push($where,['c.category_id',"eq",$category]);
        }

        if($isfree)
        {
            array_push($where,['a.is_free',"eq",$isfree]);
        }

        $categoryList = Category::where("status",1)
            ->field("id,parent_id pid,alias,name")
            ->select();

        $appList =Apps::where("app_status",1)
            ->alias("a")
            ->join("cp_apps_category_app c","c.post_id = a.id")
            ->order("update_time desc")
            ->field("a.*")
            ->where($where)
            ->group("a.id")
            ->paginate(12);

        return view('',[
            "categoryList" =>  findChild(0,1,$categoryList),
            "category"     => $category,
            "appList"      => $appList,
            'isfree'       => $isfree
        ]);
    }

    //应用详情
    public function content($shop)
    {

        $app = Apps::find($shop);

        $newAppList =  Apps::alias("a")->join("cp_apps_version b","a.id=b.app_id")
            ->order("b.update_time desc")
            ->limit(8)
            ->field("a.id,a.app_name,a.app_install,b.app_version,b.update_time")
            ->select();

        $hotAppList = Apps::order("app_install desc")
            ->limit(8)
            ->select();

        return view('',[
            "app"        => $app,
            "newAppList" => $newAppList,
            "hotAppList" => $hotAppList
        ]);

    }

    //应用下载
    public function download()
    {

        $id = $this->request->param("id");

        $appVersion = AppsVersion::where("app_id",$id)->order("create_time desc")->find();

        if(empty($appVersion['app_pack'])) $this->error("暂时没有可用的资源提供下载");

        switch (intval($appVersion['is_install'])){
            case 0:
                $this->error("该资源暂时不开发下载");
                break;
        }
        $app = Apps::where("id",$id)->find();

        switch (intval($app['is_free'])){
            case 1:

                break;
        }

        AppsVersion::where("app_id",$id)->setInc("app_install",1);

        Apps::where("id",$id)->setInc("app_install",1);

        return _download_file_download($appVersion['app_pack']);
    }
}